<template>
    <div>
      <el-input class="message" placeholder="验证码" prefix-icon="el-icon-message"
                v-model="message" @change="changeMessage"></el-input>
      <el-button :disabled="!canClick" @click="visiblePicCaptcha"
                 class="mes-btn"
                 size="medium">{{btnContent}}
      </el-button>
      <el-dialog
        title="提示"
        :visible.sync="dialogVisible"
        :modal="false"
        width="30%">
        <el-input class="input" v-model="picCaptcha" placeholder="请输入验证码"></el-input>
        <img :src="captcha" style="height:40px; width: 100px; cursor: pointer;" alt="点击更换" @click="getPicCaptcha"
             title="点击更换" />
        <el-button @click="getMessage" size="medium" :disabled="!picCaptcha">获取验证码</el-button>
      </el-dialog>
    </div>
</template>

<script>
  import {isMobile} from '@/utils/validate'

  export default {
    name: 'captcha',
    model:{
      prop:'msg',//这个字段，是指父组件设置 v-model 时，将变量值传给子组件的 msg
      event:'parent-event'//这个字段，是指父组件监听 parent-event 事件
    },
    props:{
      msg:String, //此处必须定义和model的prop相同的props，因为v-model会传值给子组件
      phoneNumber: String
    },
    data() {
      return {
        dialogVisible: false,
        message: '',
        canClick: true,
        btnContent: '发送短信验证码',
        picCaptcha:'',
        captcha: '',
        totalTime: 60
      }
    },
    methods: {
      getPicCaptcha(){
        this.captcha = "/api/captcha.jpg?phone="+this.phoneNumber+ "&t="+ new Date().getTime()
      },
      changeMessage(e){
        this.$emit('parent-event',e);
      },
      visiblePicCaptcha(){
        if (isMobile(this.phoneNumber)) {
          this.dialogVisible = true
          this.getPicCaptcha()
        }else {
          this.$message({
            type: 'error',
            message: '请填写正确的手机号',
            duration: 1500,
          })
        }
      },
      //获取验证码
      getMessage () {
        if (isMobile(this.phoneNumber)) {
          this.$http.get('/phone/code', {params: {phone: this.phoneNumber,code: this.picCaptcha}}).then(res => {
            this.dialogVisible = false
            this.countDown()
          })
        } else {
          this.$message({
            type: 'error',
            message: '请填写正确的手机号',
            duration: 1500,
          })
        }
      },
      countDown () {
        if (!this.canClick) return   //改动的是这两行代码
        this.canClick = false
        this.btnContent = this.totalTime + 's后重新发送'
        let clock = window.setInterval(() => {
          this.totalTime--
          this.btnContent = this.totalTime + 's后重新发送'
          if (this.totalTime < 0) {
            window.clearInterval(clock)
            this.btnContent = '发送短信验证码'
            this.totalTime = 60
            this.canClick = true   //这里重新开启
          }
        }, 1000)
      },
    },

  }
</script>

<style scoped>
  .message {
    width: 50% !important;
    margin-right: 10px;
  }
</style>
